const express = require('express')
const app = express()
const path = require ('path')
//托管静态文件
app.use(express.static(path.join(__dirname,'pages')))
//配置cors
const cors = require('cors')
//配置session中间件
const session = require('express-session')
app.use(session({
  secret:'keyboard cat',
  resave:false,
  saveUninitialized:true
}))
//使用cors
app.use(cors())
//创建登录api接口
app.post('/api/login',(req,res)=>{
      if(req.body.username!=='admin'||req.body.password!=='000000'){
        return res.send({status:1,msg:'登陆失败'})
      }

//登陆成功用session存储用户数据
req.session.user = req.body
req.session.islogin = true
res.send({status:0,msg:'登陆成功'})
})
//获取用户名的接口
app.get('/api/user',(req,res)=>{
        if(!req.session.islogin){
            return res.send({status:1,msg:'err'})
        }
       res.send({
        status:0,
        msg:'success',
        username:req.session.user.username
       })

})
//清空session中的数据
app.post('/api/logout',(req,res)=>{
    req.session.destroy()
    res.send({
        status:0,
        msg:'已登出'
    })
})
app.listen(80,() => {
 console.log('http://127.0.0.1:80')
})